#include "data-reader.h"

#include <cstdlib>
#include <cstdio>
#include <fstream>
#include <sstream>

using std::ofstream;
using std::ifstream;
using std::stringstream;

void Image::Print() {
  printf("#%d\n", label_);
  for (size_t i = 0; i < pixels_.size(); ++i) {
    const vector<int>& row = pixels_[i];
    for (size_t j = 0; j < row.size(); ++j) {
      if (j == 0) {
        printf("%3d", row[j]);
      } else {
        printf("%4d", row[j]);
      }
    }
    printf("\n");
  }
}

void DataReader::DumpWeights(const vector<double>& weights,
                             const string& filename) {
 printf("Dumping weights to file: %s\n", filename.c_str());
 ofstream outdata;
 outdata.open(filename.c_str());
 for (size_t i = 0; i < weights.size(); ++i) {
   outdata << weights[i] << std::endl;
 }
 outdata.close();
}

vector<double> DataReader::ReadWeights(const string& filename) {
  printf("Reading weights from file: %s\n", filename.c_str());
  vector<double> weights;
  ifstream indata;
  indata.open(filename.c_str());
  string line;
  while (getline(indata, line)) {
    stringstream ss;
    ss << line;
    if (ss.str() == "nan") {
      weights.push_back(0);
    } else {
      double val;
      ss >> val;
      weights.push_back(val);
    }
  }
  return weights;
}

vector<Image*> DataReader::GetImages(const string& filename, int limit) {
  ifstream indata;
  indata.open(filename.c_str());
  vector<Image*> images;
  Image* image = NULL;
  int cur_row = 0;
  int num = 0;
  while (!indata.eof()) {
    string line;
    getline(indata, line);
    if (line.find("#") == 0) {
      // Start of a new image
      if (image != NULL) {
        images.push_back(image);
        num++;
        if (num == limit) {
          break;
        }
      }
      image = new Image(atoi(line.substr(1).c_str()));
      cur_row = 0;
    } else {
      stringstream sstream(stringstream::in | stringstream::out);
      sstream << line;
      image->pixels_.push_back(vector<int>());
      int val;
      while (sstream >> val) {
        image->pixels_[cur_row].push_back(val);
      }
      cur_row++;
    }
    //printf("%s\n", line.c_str());
  }
  if (image != NULL) {
    images.push_back(image);
  }
  return images;
}

